<template>
  <view class="add-address-page">
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 收货人信息 -->
      <view class="form-group">
        <view class="form-label">
          <text class="required">*</text>
          <text>收货人</text>
        </view>
        <input 
          v-model="formData.contactName" 
          class="form-input" 
          placeholder="请输入收货人姓名"
          :maxlength="20"
        />
      </view>

      <!-- 手机号 -->
      <view class="form-group">
        <view class="form-label">
          <text class="required">*</text>
          <text>手机号</text>
        </view>
        <input 
          v-model="formData.contactPhone" 
          class="form-input" 
          type="number"
          :maxlength="11"
          placeholder="请输入手机号"
        />
      </view>

      <!-- 所在地区 -->
      <view class="form-group" @tap="showRegionPicker = true">
        <view class="form-label">
          <text class="required">*</text>
          <text>所在地区</text>
        </view>
        <view class="region-picker">
          <text v-if="selectedRegion" class="region-text">
            {{ formData.province }} {{ formData.city }} {{ formData.district }}
          </text>
          <text v-else class="placeholder">请选择省市区</text>
          <uni-icons type="arrowright" size="16" color="#ccc"></uni-icons>
        </view>
      </view>

      <!-- 详细地址 -->
      <view class="form-group">
        <view class="form-label">
          <text class="required">*</text>
          <text>详细地址</text>
        </view>
        <view class="address-input-wrapper">
          <textarea 
            v-model="formData.street" 
            class="address-textarea" 
            placeholder="街道、楼牌号等详细地址"
            :maxlength="100"
            auto-height
          ></textarea>
          <button class="location-btn" @tap="handleGetLocation">
            <uni-icons type="location-filled" size="18" color="#00C853"></uni-icons>
            <text class="location-text">定位</text>
          </button>
        </view>
      </view>

      <!-- 门牌号 -->
      <view class="form-group">
        <view class="form-label">
          <text>门牌号</text>
        </view>
        <input 
          v-model="formData.building" 
          class="form-input" 
          placeholder="楼栋-单元-门牌号(选填)"
          :maxlength="50"
        />
      </view>

      <!-- 地址标签 -->
      <view class="form-group">
        <view class="form-label">
          <text>地址标签</text>
        </view>
        <view class="tag-list">
          <view 
            v-for="tag in addressTags" 
            :key="tag"
            class="tag-item"
            :class="{ active: selectedTag === tag }"
            @tap="selectedTag = tag"
          >
            {{ tag }}
          </view>
        </view>
      </view>

      <!-- 设置默认地址 -->
      <view class="form-group default-switch">
        <text class="form-label">设为默认地址</text>
        <switch 
          :checked="formData.isDefault === 1" 
          color="#00C853"
          @change="onDefaultChange"
        />
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="add-address-page">
      <button class="save-btn" @tap="saveAddressData">
        {{ pageParams.isEdit ? '保存修改' : '保存' }}
      </button>
    </view>

    <!-- 地区选择器弹窗 -->
    <view v-if="showRegionPicker" class="modal-overlay" @tap="showRegionPicker = false">
      <view class="region-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">选择地区</text>
          <uni-icons type="closeempty" size="24" color="#666" @tap="showRegionPicker = false"></uni-icons>
        </view>
        
        <view class="region-tabs">
          <view 
            v-for="(tab, index) in regionTabs" 
            :key="index"
            class="region-tab"
            :class="{ active: currentTab === index }"
            @tap="currentTab = index"
          >
            {{ tab }}
          </view>
        </view>

        <view class="region-content">
          <!-- 省份列表 -->
          <scroll-view 
            v-if="currentTab === 0" 
            class="region-list" 
            scroll-y
          >
            <view 
              v-for="province in provinces" 
              :key="province.code"
              class="region-item"
              :class="{ selected: formData.province === province.name }"
              @tap="selectProvince(province)"
            >
              {{ province.name }}
              <uni-icons 
                v-if="formData.province === province.name"
                type="checkmarkempty" 
                size="20" 
                color="#00C853"
              ></uni-icons>
            </view>
          </scroll-view>

          <!-- 城市列表 -->
          <scroll-view 
            v-if="currentTab === 1" 
            class="region-list" 
            scroll-y
          >
            <view 
              v-for="city in cities" 
              :key="city.code"
              class="region-item"
              :class="{ selected: formData.city === city.name }"
              @tap="selectCity(city)"
            >
              {{ city.name }}
              <uni-icons 
                v-if="formData.city === city.name"
                type="checkmarkempty" 
                size="20" 
                color="#00C853"
              ></uni-icons>
            </view>
          </scroll-view>

          <!-- 区县列表 -->
          <scroll-view 
            v-if="currentTab === 2" 
            class="region-list" 
            scroll-y
          >
            <view 
              v-for="district in districts" 
              :key="district.code"
              class="region-item"
              :class="{ selected: formData.district === district.name }"
              @tap="selectDistrict(district)"
            >
              {{ district.name }}
              <uni-icons 
                v-if="formData.district === district.name"
                type="checkmarkempty" 
                size="20" 
                color="#00C853"
              ></uni-icons>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/store/modules/user';
import { validatePhone } from '@/utils/validate';
import { getCurrentLocation as getLocation, getRegeo } from '@/utils/amapWx';
import { addAddress, updateAddress } from '@/api/auth';

const userStore = useUserStore();

// 区分新增和编辑
const pageParams = ref({
  addressId: 0, // 0 表示新增,有值表示编辑
  isEdit: false
});

// 表单数据
const formData = ref({  
  contactName: '',
  contactPhone: '',
  province: '',
  city: '',
  district: '',
  street: '',
  building: '',
  latitude: 0,
  longitude: 0,
  isDefault: 0
});

// 地址标签
const addressTags = ['家', '公司', '学校'];
const selectedTag = ref('');

// 地区选择相关
const showRegionPicker = ref(false);
const currentTab = ref(0);
const regionTabs = computed(() => [
  formData.value.province || '省份',
  formData.value.city || '城市',
  formData.value.district || '区县'
]);

// 是否已选择地区
const selectedRegion = computed(() => 
  formData.value.province && formData.value.city && formData.value.district
);

// 模拟省市区数据
const provinces = ref([
  { code: '520000', name: '贵州省' },
  { code: '110000', name: '北京市' },
  { code: '310000', name: '上海市' },
  { code: '440000', name: '广东省' },
  { code: '510000', name: '四川省' }
]);

const cities = ref<any[]>([]);
const districts = ref<any[]>([]);

// 城市数据映射
const cityMap: Record<string, any[]> = {
  '520000': [
    { code: '520100', name: '贵阳市' },
    { code: '520200', name: '六盘水市' },
    { code: '520300', name: '遵义市' }
  ],
  '110000': [
    { code: '110100', name: '北京市' }
  ],
  '310000': [
    { code: '310100', name: '上海市' }
  ],
  '440000': [
    { code: '440100', name: '广州市' },
    { code: '440300', name: '深圳市' }
  ]
};

// 区县数据映射
const districtMap: Record<string, any[]> = {
  '520100': [
    { code: '520102', name: '南明区' },
    { code: '520103', name: '云岩区' },
    { code: '520111', name: '花溪区' },
    { code: '520112', name: '乌当区' },
    { code: '520113', name: '白云区' },
    { code: '520115', name: '观山湖区' }
  ],
  '110100': [
    { code: '110101', name: '东城区' },
    { code: '110102', name: '西城区' },
    { code: '110105', name: '朝阳区' },
    { code: '110106', name: '丰台区' }
  ],
  '440100': [
    { code: '440103', name: '荔湾区' },
    { code: '440104', name: '越秀区' },
    { code: '440105', name: '海珠区' }
  ]
};

// 页面加载时接收参数
onLoad((options: any) => {
  if (options.addressId) {
    pageParams.value.addressId = Number(options.addressId);
    pageParams.value.isEdit = true;
    
    // 如果是编辑,需要加载地址详情
    loadAddressDetail();
  }
  
  // 动态设置导航栏标题
  uni.setNavigationBarTitle({
    title: pageParams.value.isEdit ? '编辑地址' : '新增地址'
  });
});

// 加载地址详情(编辑模式)
const loadAddressDetail = async () => {
  if (!userStore.userInfo?.customerId || !pageParams.value.addressId) return;
  
  try {
    uni.showLoading({ title: '加载中...' });
    
    const { getAddressDetail } = await import('@/api/auth');
    const data: any = await getAddressDetail(
      userStore.userInfo.customerId, 
      pageParams.value.addressId
    );
    
    // 填充表单数据
    formData.value = {
      contactName: data.contactName || '',
      contactPhone: data.contactPhone || '',
      province: data.province || '',
      city: data.city || '',
      district: data.district || '',
      street: data.street || '',
      building: data.building || '',
      latitude: data.latitude || 0,
      longitude: data.longitude || 0,
      isDefault: data.isDefault || 0
    };
    
    // 如果有标签,设置选中
    if (data.tag) {
      selectedTag.value = data.tag;
    }
    
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error('加载地址详情失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
  }
};

// 选择省份
const selectProvince = (province: any) => {
  formData.value.province = province.name;
  formData.value.city = '';
  formData.value.district = '';
  
  // 加载对应城市
  cities.value = cityMap[province.code] || [];
  districts.value = [];
  
  // 切换到城市选择
  currentTab.value = 1;
};

// 选择城市
const selectCity = (city: any) => {
  formData.value.city = city.name;
  formData.value.district = '';
  
  // 加载对应区县
  districts.value = districtMap[city.code] || [];
  
  // 切换到区县选择
  currentTab.value = 2;
};

// 选择区县
const selectDistrict = (district: any) => {
  formData.value.district = district.name;
  
  // 关闭选择器
  setTimeout(() => {
    showRegionPicker.value = false;
    currentTab.value = 0;
  }, 300);
};

// 获取当前定位
const handleGetLocation = async () => {
  try {
    uni.showLoading({ title: '定位中...' });
    
    // 获取当前位置经纬度
    const location = await getLocation();
    
    console.log('定位成功:', location);
    
    // 保存经纬度
    formData.value.latitude = location.latitude;
    formData.value.longitude = location.longitude;
    
    // 调用高德地图逆地理编码获取详细地址
    const addressResult = await getRegeo(location);
    
    if (addressResult.success) {
      // 自动填充地区信息
      formData.value.province = addressResult.province;
      formData.value.city = addressResult.city;
      formData.value.district = addressResult.district;
      
      // 填充街道信息
      const street = `${addressResult.township}${addressResult.street}${addressResult.streetNumber || ''}`;
      formData.value.street = street;
      
      uni.hideLoading();
      
      uni.showToast({
        title: '定位成功',
        icon: 'success'
      });
      
      console.log('地址解析结果:', addressResult);
    } else {
      uni.hideLoading();
      
      uni.showToast({
        title: addressResult.message || '地址解析失败',
        icon: 'none'
      });
    }
  } catch (error: any) {
    uni.hideLoading();
    console.error('定位失败:', error);
    
    uni.showToast({
      title: error.message || '定位失败,请检查定位权限',
      icon: 'none'
    });
  }
};

// 切换默认地址
const onDefaultChange = (e: any) => {
  formData.value.isDefault = e.detail.value ? 1 : 0;
};

// 保存地址
const saveAddressData = async () => {
  // 表单验证
  if (!formData.value.contactName.trim()) {
    uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    });
    return;
  }

  if (!validatePhone(formData.value.contactPhone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.province || !formData.value.city || !formData.value.district) {
    uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    });
    return;
  }

  if (!formData.value.street.trim()) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    });
    return;
  }

  if (!userStore.userInfo?.customerId) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({ title: '保存中...' });

    // 调用新增地址接口   
    const submitData = {
      customerId: userStore.userInfo.customerId, // ⭐ 新增时需要传 customerId
      contactName: formData.value.contactName,
      contactPhone: formData.value.contactPhone,
      province: formData.value.province,
      city: formData.value.city,
      district: formData.value.district,
      street: formData.value.street,
      building: formData.value.building || '',
      latitude: formData.value.latitude,
      longitude: formData.value.longitude,
      isDefault: formData.value.isDefault,
      tag: selectedTag.value
    };

    // ⭐ 根据是新增还是编辑调用不同的接口
    if (pageParams.value.isEdit && pageParams.value.addressId) {
      // 编辑模式 - 调用 PUT 接口
      await updateAddress(
        userStore.userInfo.customerId,
        pageParams.value.addressId,
        submitData
      );
    } else {
      // 新增模式 - 调用 POST 接口
      await addAddress(submitData);
    }

    uni.hideLoading();

    uni.showToast({
      title: pageParams.value.isEdit ? '修改成功' : '添加成功',
      icon: 'success'
    });

    // 返回地址列表页
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);

  } catch (error) {
    uni.hideLoading();
    console.error('保存地址失败:', error);
    uni.showToast({
      title: '保存失败,请重试',
      icon: 'none'
    });
  }
};
</script>

<style scoped>
.add-address-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.form-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
}

.form-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: flex;
  align-items: center;
}

.required {
  color: #ff3b30;
  margin-right: 5rpx;
}

.form-input {
  width: 100%;
  height: 70rpx;
  font-size: 30rpx;
  color: #333;
}

.placeholder {
  color: #999;
}

.region-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70rpx;
}

.region-text {
  font-size: 30rpx;
  color: #333;
}

.address-input-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
}

.address-textarea {
  flex: 1;
  min-height: 100rpx;
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 5rpx;
  padding: 10rpx 20rpx;
  background-color: #e6f7ed;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #00C853;
  border: none;
}

.location-text {
  font-size: 24rpx;
}

.tag-list {
  display: flex;
  gap: 20rpx;
  flex-wrap: wrap;
}

.tag-item {
  padding: 15rpx 40rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
  border: 2rpx solid transparent;
}

.tag-item.active {
  background-color: #e6f7ed;
  color: #00C853;
  border-color: #00C853;
}

.default-switch {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.save-btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background-color: #00C853;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  border: none;
}

/* 地区选择弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 999;
}

.region-modal {
  width: 100%;
  height: 80vh;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.region-tabs {
  display: flex;
  border-bottom: 1rpx solid #f0f0f0;
}

.region-tab {
  flex: 1;
  text-align: center;
  padding: 25rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.region-tab.active {
  color: #00C853;
  font-weight: bold;
}

.region-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #00C853;
  border-radius: 2rpx;
}

.region-content {
  flex: 1;
  overflow: hidden;
}

.region-list {
  height: 100%;
}

.region-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  font-size: 28rpx;
  color: #333;
}

.region-item.selected {
  color: #00C853;
  background-color: #f5f5f5;
}
</style>